package org.java.web;

import com.alibaba.fastjson.JSON;
import org.java.dao.UserDao;
import org.java.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BaseServlet{

    private UserDao dao = new UserDao();
    //显示用户信息
    protected void init(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> list = dao.getList();

        request.getSession().setAttribute("list",list);

        //返回json格式的数据
        Map jsonMap = new HashMap();
        jsonMap.put("code",0);//操作成功
        jsonMap.put("msg","");//错误消息
        jsonMap.put("data",list);//存放地址

        String json= JSON.toJSONString(jsonMap);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }

    //编辑
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得修改的id
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String number = request.getParameter("number");
        Integer state = Integer.parseInt(request.getParameter("state"));

        dao.update(id,name,pwd,number,state);

    }
}
